from django.shortcuts import render
from django.db.models import Q
from rest_framework import viewsets, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, OpenApiParameter
from apps.data_source.models import StockBasic, StockDaily, FinancialIndicator
from apps.data_source.tasks import sync_stock_basic, sync_daily_data, sync_financial_data
from .serializers import (
    StockBasicSerializer, StockDailySerializer, 
    FinancialIndicatorSerializer, StockDetailSerializer
)


class StockViewSet(viewsets.ReadOnlyModelViewSet):
    """
    股票基本信息视图集
    """
    queryset = StockBasic.objects.all()
    serializer_class = StockBasicSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['industry', 'market']
    search_fields = ['ts_code', 'symbol', 'name']
    ordering_fields = ['ts_code', 'list_date']
    ordering = ['ts_code']
    
    @extend_schema(
        parameters=[
            OpenApiParameter(name='industry', description='行业', required=False, type=str),
            OpenApiParameter(name='market', description='市场类型', required=False, type=str),
            OpenApiParameter(name='search', description='搜索(代码/名称)', required=False, type=str),
        ],
        description='获取股票列表',
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)
    
    @extend_schema(
        description='获取股票详情',
    )
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = StockDetailSerializer(instance)
        return Response(serializer.data)
    
    @extend_schema(
        description='同步股票基本信息',
    )
    @action(detail=False, methods=['post'], url_path='sync-basic')
    def sync_basic(self, request):
        """同步股票基本信息"""
        task = sync_stock_basic.delay()
        return Response({
            'message': '股票同步任务已提交',
            'task_id': task.id
        })
    
    @extend_schema(
        parameters=[
            OpenApiParameter(name='days', description='同步天数', required=False, type=int),
        ],
        description='同步股票日线数据',
    )
    @action(detail=True, methods=['post'], url_path='sync-daily')
    def sync_daily(self, request, pk=None):
        """同步指定股票的日线数据"""
        days = request.data.get('days', 30)
        task = sync_daily_data.delay(pk, days)
        return Response({
            'message': f'股票 {pk} 日线数据同步任务已提交',
            'task_id': task.id
        })


class StockDailyViewSet(viewsets.ReadOnlyModelViewSet):
    """
    股票日线数据视图集
    """
    serializer_class = StockDailySerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['stock', 'trade_date']
    ordering_fields = ['trade_date', 'close', 'pct_chg', 'vol']
    ordering = ['-trade_date']
    
    def get_queryset(self):
        """可根据日期范围筛选"""
        queryset = StockDaily.objects.all()
        
        # 日期范围筛选
        start_date = self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')
        
        if start_date:
            queryset = queryset.filter(trade_date__gte=start_date)
        if end_date:
            queryset = queryset.filter(trade_date__lte=end_date)
        
        return queryset
    
    @extend_schema(
        parameters=[
            OpenApiParameter(name='stock', description='股票ID', required=False, type=str),
            OpenApiParameter(name='start_date', description='开始日期', required=False, type=str),
            OpenApiParameter(name='end_date', description='结束日期', required=False, type=str),
        ],
        description='获取股票日线数据列表',
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)


class StockSearchView(APIView):
    """
    股票搜索视图
    """
    @extend_schema(
        parameters=[
            OpenApiParameter(name='q', description='搜索关键词', required=True, type=str),
        ],
        description='搜索股票',
    )
    def get(self, request):
        """
        搜索股票，支持代码、名称模糊搜索
        """
        query = request.query_params.get('q', '')
        if not query or len(query) < 2:
            return Response({
                'message': '搜索关键词至少需要2个字符'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 模糊搜索
        stocks = StockBasic.objects.filter(
            Q(ts_code__icontains=query) | 
            Q(symbol__icontains=query) | 
            Q(name__icontains=query)
        )[:20]  # 限制返回数量
        
        serializer = StockBasicSerializer(stocks, many=True)
        return Response(serializer.data)
